package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gmall.item.service.CacheOpsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author:ahang
 * @create:2022-10-17 23:18
 * @Description:
 */
@Service
public class CacheOpsServiceImpl implements CacheOpsService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 查询redis
     * @param key
     * @param Clazz
     * @param <T>
     * @return
     */
    @Override
    public <T> T getCacheData(String key, Class<T> Clazz) {
        String json = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(json)){
            return null;
        }else{
            T t = Jsons.toObject(json, Clazz);
            return t;
        }
    }

    /**
     * 放入缓存
     * @param
     * @param object
     */
    @Override
    public void setDate(String key, Object object, Long ttl, TimeUnit timeUnit) {

        String jsonData = object==null? RedisConst.TEMP_DATA:Jsons.tostr(object);
        //缓存中的所有数据都应该有一个过期时间--临时数据缓存时间短一点
        if(object == null){
            stringRedisTemplate.opsForValue().set(key,jsonData,RedisConst.TEMP_DATA_TTL,RedisConst.TEMP_DATA_TTL_UNIT);
        }

        stringRedisTemplate.opsForValue().set(key,jsonData,ttl,timeUnit);

    }
}
